package pbx.service;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import pbx.model.Sip;
import security.service.SecurityService;


@Stateless
public class PbxUploadService {

	
	@EJB
	SecurityService securityService;

	@EJB
	SipService sipService;



    // NUEVO!!!
    public Integer uploadSip(XSSFWorkbook book) {

        int out = 0;
        XSSFWorkbook wb = (XSSFWorkbook) book;
        int numSheets = book.getNumberOfSheets();
        System.out.println("Sheets Total: " + numSheets);

        // READ SHEETS
        for (int i = 0; i < 1; i++) {
            System.out.println("Reading Sheet Number: " + i);

            XSSFSheet sheet = wb.getSheetAt(i);
            int numRows = 621;
            System.out.println("# Rows: " + numRows);

            // READ ROWS
            int firstrow = 1;
            for (int x = firstrow; x <= numRows; x++) {
                Row row = sheet.getRow(x);
                System.out.println("Reading Row Number: " + x);

                // MANAGE SIP
                System.out.println("Row:" + x + "MANAGE SIP");

                Double doublecode = row.getCell(0).getNumericCellValue();
                String mac = row.getCell(2).getStringCellValue().trim();
                String ip = row.getCell(3).getStringCellValue().trim();

                Double doublemodel = row.getCell(4).getNumericCellValue();

                // Organization organization = null;
                Integer intcode = doublecode.intValue();
                Integer intmodel = doublemodel.intValue();

                String code = intcode.toString();
                String model =  intmodel.toString();
                Sip sip = sipService.getByCode(code);

                if (sip == null) {
                    System.out.println("CREATE SIP");
                    sip = new Sip();
                    sip.setCode(code);
                    sip.setMac(mac);
                    sip.setModel(model);
                    sip.setIpaddr(ip);
                    // sip.setOrganization_id(organization.getId());
                    sipService.save(sip);
                    System.out.println("SAVE SIP: " + code);
                }

                System.out.println("-------------------------------------------------------------------");
            }
            out = 1;
        }

        return out;

    }
	
}
